<template>
  <el-dropdown @visible-change="visibleChange">
    <el-icon><More /></el-icon>

    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="updateTemplate"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/chong_mm.png"
            />修改信息
          </div></el-dropdown-item
        >
        <el-dropdown-item @click="previewTemplate"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/yu_lan_xiao.png"
            />预览
          </div></el-dropdown-item
        >
        <el-dropdown-item @click="editTemplate"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/bian_ji_xiao.png"
            />编辑模板
          </div></el-dropdown-item
        >
        <el-dropdown-item @click="exportTemplate"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/dao_chu_xiao.png"
            />导出
          </div></el-dropdown-item
        >
        <el-dropdown-item @click="generateCodeHandle"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/shengc_daima_xiao.png"
            />生成代码
          </div></el-dropdown-item
        >
        <el-dropdown-item
          v-if="props.obj.pushStatus == 0"
          @click="releaseTemplate(1)"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/fa_bu_xiao.png"
            />发布
          </div></el-dropdown-item
        >

        <el-dropdown-item v-else @click="releaseTemplate(0)">
          <div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/che_xiao_xiao.png"
            />撤销
          </div></el-dropdown-item
        >
        <el-dropdown-item @click="deleteTemplateHandle"
          ><div class="btn flex items-center">
            <img
              class="w-[12px] mr-[5px]"
              src="@renderer/assets/images/shan_chu_xiao.png"
            />删除
          </div></el-dropdown-item
        >
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <SaveDialog
    ref="saveDialog"
    :configJson="configsJson"
    :layoutJson="layout"
    @update="confirmUpdated"
    @close="emit('requery')"
  />
</template>
<script setup lang="ts">
import { ref, onMounted, provide } from "vue";
import { useRouter } from "vue-router";
import SaveDialog from "@renderer/components/saveDialog/index.vue";
import { beforPublicLayout } from "@renderer/utils/handleTooLong";
import {
  codeToProject,
  generateCode,
  exportFile,
} from "@renderer/utils/operationCode";
import {
  getTemplateDetail,
  deleteTemplate,
  publishTemplate,
} from "@renderer/api/projectMenu";
const { ipcRenderer } = window;
const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  obj: {
    type: Object,
    default: () => ({}),
  },
});
provide("refreshPage", {});
let router = useRouter();
let emit = defineEmits(["requery"]);
let saveDialog = ref(null);
let currentDetails = ref(null);
let configsJson = ref();
let layout = ref();
let currentObj = ref<any>({});
const visibleChange = async (val) => {};

const getDetails = async () => {
  const res: any = await getTemplateDetail(props.id);
  if (res.code == 200) {
    currentObj.value = res.data;
  } else {
    currentObj.value = {};
    ElMessage.error(res.msg || "获取详情失败");
  }
};
onMounted(() => {});
const previewTemplate = () => {
  ipcRenderer.invoke("open-win", {
    url: `/previewOutLine?id=${props.id}&type=template`,
  });
};
const editTemplate = () => {
  router.push({
    path: "/editContainer",
    query: {
      id: props.id,
    },
  });
};
const updateTemplate = () => {
  getTemplateDetail(props.id).then((res: any) => {
    // form.value = res.data;
    currentDetails.value = res.data;
    layout.value = JSON.parse(res.data.detail.layoutJson);
    configsJson.value = JSON.parse(res.data.detail.configJson);
    saveDialog.value.dialogVisible = true;
    saveDialog.value.init("edit", res.data);
  });
};

const confirmUpdated = () => {
  if (currentDetails.value.pushStatus == 1) {
    ElMessageBox.confirm(
      "检测到模板已经发布，是否同步到资源市场？",
      "已保存成功",
      {
        confirmButtonText: "同步",
        cancelButtonText: "取消",
      }
    ).then(() => {
      releaseTemplate(1);
    });
  }
};
const exportTemplate = async () => {
  await getDetails();
  await exportFile(
    currentObj.value.name,
    JSON.parse(currentObj.value.detail.layoutJson),
    JSON.parse(currentObj.value.detail.configJson)
  );
};

const generateCodeHandle = async () => {
  await getDetails();
  const { result, allComponentsArrsList } = await generateCode(
    JSON.parse(currentObj.value.detail.layoutJson),
    JSON.parse(currentObj.value.detail.configJson)
  );
  codeToProject(result, allComponentsArrsList);
};
const releaseTemplate = async (type) => {
  await getDetails();
  let formData = new FormData();
  formData.append("id", props.id);
  formData.append("pushStatus", type);

  if (type == 1) {
    // 去掉数据源信息
    let layoutList = beforPublicLayout(
      JSON.parse(currentObj.value.detail.layoutJson)
    );
    formData.append("configJson", currentObj.value.detail.configJson);
    formData.append("layoutJson", JSON.stringify(layoutList));
  }

  publishTemplate(formData).then((res: any) => {
    if (res.code == 200) {
      ElMessage.success(type == 1 ? "发布成功" : "撤销成功");
      emit("requery");
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  });
};
const deleteTemplateHandle = () => {
  ElMessageBox.confirm("此操作将永久删除该模板, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await deleteTemplate([props.id]);
      console.log(res);
      if (res.code == 200) {
        ElMessage.success("删除成功");
        emit("requery");
      }
    })
    .catch(() => {});
};
</script>
